package cn.piggy.gateway.core.datasource.unpooled;

import cn.piggy.gateway.core.config.ConfigHelper;
import cn.piggy.gateway.core.datasource.connection.Connection;
import cn.piggy.gateway.core.datasource.DataSource;
import cn.piggy.gateway.core.datasource.connection.DubboConnection;
import cn.piggy.gateway.core.datasource.connection.HttpConnection;
import cn.piggy.gateway.core.datasource.connection.PiggyConnection;
import cn.piggy.gateway.core.http.HttpStatement;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.service.GenericService;

import java.util.LinkedList;
import java.util.Map;


public class UnpooledDataSource implements DataSource {

    private ConfigHelper configHelper;
    private HttpStatement httpStatement;

    @Override
    public Connection getConnection() {
        String application = httpStatement.getApplication();
        Map<String, LinkedList<String>> servers = configHelper.getServers();
        LinkedList<String> list = servers.get(application);
        if(list==null||list.size()==0){
            throw new RuntimeException("system not boot");
        }
        switch (httpStatement.getMethodType()) {
            case "HTTP":
                return new HttpConnection(list);
            case "DUBBO":
                String interfaceName = httpStatement.getInterfaceName();
                // 获取服务
                ApplicationConfig applicationConfig = configHelper.getApplicationConfig(application);
                RegistryConfig registryConfig = configHelper.getRegistryConfig(application);
                ReferenceConfig<GenericService> reference = configHelper.getReferenceConfig(application+"##"+interfaceName);
                return new DubboConnection(applicationConfig, registryConfig, reference);
            case "MYSELF":
                return new PiggyConnection(application,list);
            default:
                break;
        }
        throw new RuntimeException("DataSourceType：" + httpStatement.getMethodType() + "没有对应的数据源实现");
    }

    public void setConfiguration(ConfigHelper configHelper) {
        this.configHelper = configHelper;
    }

    public void setHttpStatement(HttpStatement httpStatement) {
        this.httpStatement = httpStatement;
    }


}
